package com.pccc.batch.config.remotepartition.asyn;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.integration.partition.StepExecutionRequestHandler;
import org.springframework.context.ApplicationListener;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import com.pccc.batch.config.remotepartition.util.HttpUtil;

@Component
public class AsynStepExectHandler implements ApplicationListener<AsynStepEvent> {
	
	private static final Logger log = LoggerFactory.getLogger(AsynStepExectHandler.class);

	private final StepExecutionRequestHandler stepExecutionRequestHandler;
	
	
	public AsynStepExectHandler(StepExecutionRequestHandler stepExecutionRequestHandler) {
		this.stepExecutionRequestHandler = stepExecutionRequestHandler;
	}
	
	@Override
	public void onApplicationEvent(AsynStepEvent event) {
		StepExecution stepExecution = stepExecutionRequestHandler.handle(event.getStepRequest());
		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
			ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
			objectStream.writeObject(stepExecution);
			objectStream.flush();
			objectStream.close();
			byte[] bytes = byteStream.toByteArray();
			HttpHeaders header = new HttpHeaders();
			header.put("correlationId", Arrays.asList(event.getCorrelationId()));
			header.put("sequenceNumber", Arrays.asList(event.getSequenceNumber()));
			header.put("sequenceSize", Arrays.asList(event.getSequenceSize()));
			header.put("Content-Type", Arrays.asList("application/x-java-serialized-object"));
			HttpUtil.post("http://127.0.0.1:8088/reply", header, bytes);
		} catch(Exception e) {
			log.error(e.getMessage(),e);
		}
	}

}
